package ru.inse.core.dao;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.management.Query;
import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

import ru.inse.core.domain.BaseEntity;


public abstract class AbstractDao<E extends BaseEntity>
    implements IDao<E>
{
    
    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource dataSource)
    {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    public JdbcTemplate getJdbcTemplate()
    {
        return jdbcTemplate;
    }

    abstract public String getTableName();
    
    
    @Transactional
    public void remove(Long id)
    {
        String sql = String.format("delete from %s where id = ?", getTableName());
        jdbcTemplate.update(sql, id);
    }

    @Transactional
    public int removeAll()
    {
        String sql = String.format("delete from %s", getTableName());
        return jdbcTemplate.update(sql);
    }

    public Long count()
    {
        return count(null);
    }

    
    @Transactional(readOnly = true)
    @Override
    public Long count(ICriteriaAppender appender)
    {
        String sql = String.format("select count(*) from %s", getTableName());
        List<Object> params = new LinkedList<Object>();
        if (appender != null)
        {
            sql = appender.append(sql, params);
        }
        System.out.println(sql);
        return getJdbcTemplate().queryForLong(sql, params.toArray(new Object[params.size()]));
    }


}
